import express from "express";
import { Category, BookInfo } from "../models/model.js";
import {
  addCategory,
  setCategory,
  getBooksByCategory,
} from "../handlers/categoriesHandler.js";

const router = express.Router();

// 添加分类
router.post("/", async (req, res, next) => {
  try {
    const category = await addCategory(req.body);
    res.status(201).json(category);
  } catch (err) {
    next(err);
  }
});

// 更新分类
router.put("/:id", async (req, res, next) => {
  try {
    const [updated] = await Category.update(req.body, {
      where: { id: req.params.id },
    });
    if (updated) {
      const category = await Category.findByPk(req.params.id);
      res.json(category);
    } else {
      res.status(404).json({ error: "Category not found" });
    }
  } catch (err) {
    next(err);
  }
});

// 删除分类
router.delete("/:id", async (req, res, next) => {
  try {
    const deleted = await Category.destroy({
      where: { id: req.params.id },
    });
    if (deleted) {
      res.status(204).end();
    } else {
      res.status(404).json({ error: "Category not found" });
    }
  } catch (err) {
    next(err);
  }
});

// 获取所有分类
router.get("/", async (req, res, next) => {
  try {
    const categories = await Category.findAll();
    res.json(categories);
  } catch (err) {
    next(err);
  }
});

// 设置书籍分类
router.post("/:id/books", async (req, res, next) => {
  try {
    await setCategory(req.body.bookIds, req.params.id);
    res.status(204).end();
  } catch (err) {
    next(err);
  }
});

// 获取分类下的书籍
router.get("/:id/books", async (req, res, next) => {
  try {
    const books = await getBooksByCategory(req.params.id);
    res.json(books);
  } catch (err) {
    next(err);
  }
});

export default router;
